package com.nihome.entershopinfo.fragments;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nihome.entershopinfo.Constants;
import com.nihome.entershopinfo.R;
import com.nihome.entershopinfo.application.SysApplication;
import com.nihome.entershopinfo.dialog.FinishDialog;
import com.nihome.entershopinfo.dialog.ImagePickDialog;
import com.nihome.entershopinfo.dialog.LoadingDialog;
import com.nihome.entershopinfo.entity.User;
import com.nihome.entershopinfo.entity.request.MoneyVoucherInfoReq;
import com.nihome.entershopinfo.entity.request.UploadImgReq;
import com.nihome.entershopinfo.entity.response.ExpandsLogRes;
import com.nihome.entershopinfo.entity.response.ResponseBase;
import com.nihome.entershopinfo.entity.response.UploadImgRes;
import com.nihome.entershopinfo.ui.HomePageActivity;
import com.nihome.entershopinfo.ui.PermissionsActivity;
import com.nihome.entershopinfo.utils.Base64Util;
import com.nihome.entershopinfo.utils.BitmapUtils;
import com.nihome.entershopinfo.utils.ImagePicker;
import com.nihome.entershopinfo.utils.Log;
import com.nihome.entershopinfo.utils.PermissionsChecker;
import com.nihome.entershopinfo.utils.RequestAPI;
import com.nihome.entershopinfo.utils.StringUtils;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Response;

/**
 * Created by Carson on 2017/7/26.
 */
public class MoneyVoucherFragment extends Fragment implements View.OnClickListener, ImagePickDialog.DialogSelectedListener{
    private static final String TAG = "MoneyVoucherFragment";
    private static final int IMG_1 = 1;
    private static final int IMG_2 = 2;
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    static final String[] PERMISSIONS = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    private static final int REQUEST_PERMISSION = 100;  //权限请求
    private ImagePickDialog imagePickDialog;
    private ImagePicker mImagePicker;
    private Uri cameraUri;
    private Uri cutImgUri;
    private int IMG_TYPE;


    private Context mContext;
    private Gson mGson;
    private User mUser;
    private LoadingDialog dialog;

    private int selectType;
    private short handlerType;
    private ExpandsLogRes expandsLog;
    private String auditId;

    private ImageView imgBtn_1;
    private ImageView imgBtn_2;
    private TextView voucherBack;
    private TextView voucherNext;

    private String reqImg_1;
    private String reqImg_2;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mGson = new Gson();
        dialog = new LoadingDialog(mContext);
        mUser = SysApplication.getInstance().getmUser();
        mPermissionsChecker = new PermissionsChecker(mContext);
        expandsLog = getArguments().getParcelable(Constants.DATA);
        auditId = expandsLog.getOtherInfoResponseDTO().getAuditId();
        if (StringUtils.isEmpty(expandsLog.getOtherInfoResponseDTO().getAmountFirstVerifyPhotoId()) &&
                StringUtils.isEmpty(expandsLog.getOtherInfoResponseDTO().getAmountSecondVerifyPhotoId())) {
            handlerType = Constants.NEW;
        } else{
            handlerType = Constants.UPDATE;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_money_voucher, container, false);
        imgBtn_1 = (ImageView) view.findViewById(R.id.money_voucher_1);
        imgBtn_2 = (ImageView) view.findViewById(R.id.money_voucher_2);
        voucherBack = (TextView) view.findViewById(R.id.voucher_info_back);
        voucherNext = (TextView) view.findViewById(R.id.voucher_info_go_next);

        imgBtn_1.setOnClickListener(this);
        imgBtn_2.setOnClickListener(this);
        voucherBack.setOnClickListener(this);
        voucherNext.setOnClickListener(this);
        if (handlerType == Constants.UPDATE) initData();
        return view;
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            expandsLog = getArguments().getParcelable(Constants.DATA);
            auditId = expandsLog.getOtherInfoResponseDTO().getAuditId();
            if (StringUtils.isEmpty(expandsLog.getOtherInfoResponseDTO().getAmountFirstVerifyPhotoId()) &&
                    StringUtils.isEmpty(expandsLog.getOtherInfoResponseDTO().getAmountSecondVerifyPhotoId())) {
                handlerType = Constants.NEW;
            } else{
                handlerType = Constants.UPDATE;
            }
        }
        if (handlerType == Constants.NEW) viewInit();
        if (handlerType == Constants.UPDATE) initData();
    }


    private void initData(){
        Picasso.with(mContext).load(expandsLog.getOtherInfoResponseDTO().getAmountFirstVerifyPhoto()).
                placeholder(R.drawable.loading).resize(200, 200).into(imgBtn_1);
        Picasso.with(mContext).load(expandsLog.getOtherInfoResponseDTO().getAmountSecondVerifyPhoto()).
                placeholder(R.drawable.loading).resize(200, 200).into(imgBtn_2);
        reqImg_1 = expandsLog.getOtherInfoResponseDTO().getAmountFirstVerifyPhotoId();
        reqImg_2 = expandsLog.getOtherInfoResponseDTO().getAmountSecondVerifyPhotoId();
    }

    private void viewInit() {
        imgBtn_1.setImageResource(R.drawable.upload_img);
        imgBtn_2.setImageResource(R.drawable.upload_img);
        reqImg_1 = "";
        reqImg_2 = "";
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.money_voucher_1:
                IMG_TYPE = IMG_1;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                        startPermissionsActivity();
                    } else {
                        showDialog();
                    }
                } else {
                    showDialog();
                }
                break;
            case R.id.money_voucher_2:
                IMG_TYPE = IMG_2;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                        startPermissionsActivity();
                    } else {
                        showDialog();
                    }
                } else {
                    showDialog();
                }
                break;
            case R.id.voucher_info_back:
                ((HomePageActivity) getActivity()).moneyVoucherBack();
                break;
            case R.id.voucher_info_go_next:
                if (check()) submit();
                else Toast.makeText(mContext, getString(R.string.submit_prompt), Toast.LENGTH_SHORT).show();
                break;
        }
    }


    private Boolean check(){
        if (StringUtils.isEmpty(reqImg_1)) return false;
        if (StringUtils.isEmpty(reqImg_2)) return false;
        return true;
    }

    void finishXCX(){
        FinishDialog finishDialog = new FinishDialog(mContext);
        finishDialog.setListener(new FinishDialog.FinishDialogListener() {
            @Override
            public void onFinish() {
                ((HomePageActivity)getActivity()).homeFinish();
            }
        });
        finishDialog.show();
    }


    private void submit(){
        dialog.show(getString(R.string.load_text));
        MoneyVoucherInfoReq infoReq = new MoneyVoucherInfoReq();
        infoReq.setAuditId(auditId);
        infoReq.setFirstPhotoId(reqImg_1);
        infoReq.setSecondPhotoId(reqImg_2);
        Log.e(TAG, "submit json = " + mGson.toJson(infoReq));
        OkHttpUtils.postString().url(RequestAPI.MONEY_VOUCHER_URL)
                .content(new Gson().toJson(infoReq))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build().execute(new SubmitInfoCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, e + "");
                dialog.dismiss();
                if (e instanceof UnknownHostException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketTimeoutException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof IOException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }

                Toast.makeText(mContext, getString(R.string.service_error), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ResponseBase<String> response, int id) {
                dialog.dismiss();
                switch (Integer.valueOf(response.getResultCode())) {
                    case Constants.REQ_SUCCESS:
                        Toast.makeText(mContext, getString(R.string.upload_success), Toast.LENGTH_SHORT).show();
                        finishXCX();
                        break;
                    default:
                        Toast.makeText(mContext, response.getMsg(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    abstract class SubmitInfoCallback extends Callback<ResponseBase<String>> {
        @Override
        public ResponseBase<String> parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            Log.e(TAG, string);
            Type jsonType = new TypeToken<ResponseBase<String>>(){}.getType();
            ResponseBase<String> res = mGson.fromJson(string, jsonType);
            return res;
        }
    }



    /** 上传图片 */
    private void uploadImgService(){
        dialog.show(getString(R.string.load_text));
        Log.e(TAG, "image path = " + cutImgUri.getPath());
        String img = "data:image/png;base64,";
        img +=  Base64Util.encode(BitmapUtils.FileTobyte(new File(cutImgUri.getPath())));
        UploadImgReq uploadImgReq = new UploadImgReq();
        uploadImgReq.setFileBase64Data(img);
        uploadImgReq.setUserId(mUser.getUserId());
        OkHttpUtils.postString().url(RequestAPI.UPLOAD_IMG_URL)
                .content(new Gson().toJson(uploadImgReq))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build().execute(new UploadImgCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dialog.dismiss();
                Toast.makeText(mContext, getString(R.string.service_error), Toast.LENGTH_SHORT).show();
                Log.e(TAG, e + "");
            }

            @Override
            public void onResponse(ResponseBase<UploadImgRes> response, int id) {
                dialog.dismiss();
                switch (Integer.valueOf(response.getResultCode())) {
                    case Constants.REQ_SUCCESS:
                        if (IMG_TYPE == IMG_1) {
                            reqImg_1 = response.getResult().getFileId();
                            Picasso.with(mContext).load(response.getResult().getFileUrl()).
                                    placeholder(R.drawable.loading).resize(200, 200).into(imgBtn_1);
                        }
                        if (IMG_TYPE == IMG_2) {
                            reqImg_2 = response.getResult().getFileId();
                            Picasso.with(mContext).load(response.getResult().getFileUrl()).
                                    placeholder(R.drawable.loading).resize(200, 200).into(imgBtn_2);
                        }
                        break;
                    default:
                        Toast.makeText(mContext, response.getMsg(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    abstract class UploadImgCallback extends Callback<ResponseBase<UploadImgRes>> {
        @Override
        public ResponseBase<UploadImgRes> parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            Log.e(TAG, string);
            Type jsonType = new TypeToken<ResponseBase<UploadImgRes>>(){}.getType();
            ResponseBase<UploadImgRes> res = mGson.fromJson(string, jsonType);
            return res;
        }
    }


    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(getActivity(), REQUEST_PERMISSION,
                PERMISSIONS);
    }

    private void showDialog(){
        if (imagePickDialog == null) imagePickDialog = new ImagePickDialog(mContext);
        imagePickDialog.setDialogSelectedListener(this);
        imagePickDialog.show();
    }

    @Override
    public void onPhone() {
        Log.e(TAG, "相册........");
        if (mImagePicker == null) mImagePicker = new ImagePicker(getActivity(), this);
        mImagePicker.pickOnphone();
    }

    @Override
    public void onCapture() {
        Log.e(TAG, "拍照........");
        if (mImagePicker == null) mImagePicker = new ImagePicker(getActivity(), this);
        cameraUri = mImagePicker.openCamera();
    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case ImagePicker.REQUEST_CAPTURE:
                    cutImgUri = mImagePicker.cropPhoto(cameraUri);
                    break;
                case ImagePicker.REQUEST_PICK_IMAGE:
                    cameraUri = data.getData(); //获取系统返回的照片的Uri
                    cutImgUri = mImagePicker.cropPhoto(cameraUri);
                    break;
                case ImagePicker.REQUEST_PICTURE_CUT:
                    uploadImgService();
                    break;
            }
        }
    }
}
